package com.suse.common.config.redis;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.suse.common.util.core.UUIDUtil;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 默认的Redis锁
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-10-24 21:49
 */
@Component
public class RedisLock implements InitializingBean {

    protected static final long DEFAULT_LOCK_TTL = 30;

    protected static final TimeUnit DEFAULT_LOCK_TTL_UNIT = TimeUnit.SECONDS;

    private static RedisClient redisClient;

    private static StringRedisTemplate stringRedisTemplate;

    private final String mark = UUIDUtil.generateUUID();

    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT = new DefaultRedisScript<>();

    static {
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        // 必须指定返回结果类型，否则报错
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    private long ttl = DEFAULT_LOCK_TTL;

    private TimeUnit unit = DEFAULT_LOCK_TTL_UNIT;

    private final String lock;

    public RedisLock() {
        lock = mark;
    }

    public RedisLock(String lock) {
        this.lock = lock;
    }

    public RedisLock(String lock,long ttl,TimeUnit unit) {
        this.lock = lock;
        this.ttl = ttl;
        this.unit = unit;
    }

    public boolean trylock() {
        return redisClient.setnx(lock,mark,ttl,unit);
    }

    public void unlock() {
        // 使用LUA脚本保证释放锁的原子性
        stringRedisTemplate.execute(UNLOCK_SCRIPT, ListUtil.of(lock),mark);
    }

    @Override
    public void afterPropertiesSet() {
        redisClient = SpringUtil.getBean(RedisClient.class);
        stringRedisTemplate = SpringUtil.getBean(StringRedisTemplate.class);
    }

}
